<?php
/**
 * Created by PhpStorm.
 * User: Jason
 * Date: 2017/7/22
 * Time: 14:42
 */

namespace Api\Provider\Admin;


use Api\Provider\IndexProvider;
use Api\Service\ImageService;
use Api\Service\PageService;
use Api\Service\ScoreSheetService;
use Api\Service\SheetCommentService;
use Api\Service\SheetFavoriteService;
use Api\Service\SheetPurchaseService;
use Api\Service\SheetRecordService;
use Api\Service\SheetService;
use Api\Service\UserMemberService;
use Api\Service\UserService;
use Think\Page;
use Think\Log;

class SheetProvider extends IndexProvider
{
  /**
   * 获取曲谱详情
   */
  public function getSheetDetailBySheetId($param)
  {
    $sheetId = $param['sheet_id'];
    $uid = $param['uid'];
    if (empty($sheetId) || empty($uid)) {
      $this->fail('600');
    }

    $list = M('Sheet')->where(array('id' => $sheetId))->field('id, name, singer, song_name, desc, create_time, comment_count, fav_count')->select();
    $sheetDetail = $list[0];

    /*//判断曲谱是否收费
    if($sheetDetail['is_charge']) {
        //判断是否会员
        $user = new UserMemberService();
        $verify = $user->verifyMember($uid);
        if (!$verify) {
            //判断是否购买曲谱
            $sheetService = new SheetPurchaseService();
            $sheetPurchase = $sheetService->verifySheetPurchase($param);
            if (!$sheetPurchase) {
                $sheetDetail['have_pay'] = 0;
            } else {
                $sheetDetail['have_pay'] = 1;
            }
        } else {
            $sheetDetail['have_pay'] = 1;
        }
    }*/
    //判断是否已喜欢
    $map = array(
      'user_id' => $uid,
      'sheet_id' => $sheetId,
      'is_delete' => 0
    );
    $isFav = M('SheetFavorite')->where($map)->select();
    if ($isFav) {
      $sheetDetail['is_favorite'] = 1;
    } else {
      $sheetDetail['is_favorite'] = 0;
    }

    //获取曲谱图片
    $imageService = new ImageService();
    $image = $imageService->getImageUrlBySheetId($sheetId);
    $sheetDetail['image'] = $image;

    //记录点击数
    M('sheet')->where(array('id' => $sheetId))->setInc('click_count');
    //记录当日点击数
    $map = array(
      'sheet_id' => $sheetId,
      'date' => date('Y-m-d', time())
    );
    $dailyClick = M('sheetDailyView')->where($map)->find();
    if (!empty($dailyClick)) {
      M('sheetDailyView')->where($map)->setInc('click_count');
    } else {
      $data = array(
        'sheet_id' => $sheetId,
        'date' => date('Y-m-d', time()),
        'click_count' => 1,
      );
      M('sheetDailyView')->add($data);
    }

    $this->success($sheetDetail, 200);
  }

  /**
   * 喜欢曲谱
   */
  public function addFavSheet($param)
  {
    if (empty($param['uid']) || empty($param['sheet_id'])) {
      $this->fail(600);
    }
    $service = new SheetFavoriteService();
    try {
      //添加至用户收藏曲谱表
      $id = $service->addFavSheet($param);
      $this->success('', 200);
    } catch (\Exception $e) {
      $this->fail(500, '', $e->getMessage());
    }
  }

  /**
   * 获取用户喜欢的曲谱列表
   */
  public function getFavSheet($param)
  {
    if (empty($param['uid'])) {
      $this->fail(600);
    }
    $service = new SheetFavoriteService();
    $sheetList = $service->getFavSheet($param);

    $this->success($sheetList, 200);
  }

  /**
   * 收藏曲谱至指定谱单中
   */
  public function collectSheet($param)
  {
    if (empty($param['uid']) || empty($param['sheet_id']) || empty($param['score_id'])) {
      $this->fail(600);
    }
    $service = new ScoreSheetService();
    try {
      $res = $service->addSheetToScore($param);
      if (!$res) {
        $this->fail(500, '', array('曲谱已存在'));
      }
      $this->success('', 200);
    } catch (\Exception $e) {
      $this->fail(500, '', $e->getMessage());
    }

  }

  /**
   * 将曲谱从谱单中移除
   */
  public function delFromScore($param)
  {
    if (empty($param['uid']) || empty($param['sheet_id']) || empty($param['score_id'])) {
      $this->fail(600);
    }
    $service = new ScoreSheetService();
    $res = $service->delFromScore($param);
    if ($res === false) {
      $this->fail(500, '', array('用户非谱单创建者'));
    } elseif ($res) {
      $this->success('', 200);
    } else {
      $this->fail(500);
    }
  }

  /**
   * 搜索曲谱
   */
  public function getSheetBySearchName($param)
  {
    $keywords = explode(' ', $param['name']);
    foreach ($keywords as $key => $keyword) {
      $keywordArr[] = array('like', '%' . $keyword . '%');
    }

    $map = array(
      'name' => $keywordArr,
      'status' => array('neq', -1),
      'is_delete' => 0
    );

    $service = new SheetService();
    $result = $service->getSheetListByMap($map, $param);
    $this->success($result, 200);
  }

  /**
   * 添加评论
   */
  public function addComment($param)
  {
    if (empty($param['uid']) || empty($param['sheet_id']) || empty($param['remark'])) {
      $this->fail(600);
    }
    $service = new SheetCommentService();
    try {
      $param['remark'] = htmlspecialchars($param['remark']);
      $res = $service->addComment($param);
      $this->success('', 200, '操作成功');
    } catch (\Exception $e) {
      $this->fail(500, '', $e->getMessage());
    }
  }

  /**
   * 获取评论
   */
  public function getComment($param)
  {
    if (empty($param['sheet_id'])) {
      $this->fail(600);
    }
    $service = new SheetCommentService();
    $comment = $service->getComment($param);
    if ($comment) {
      $this->success($comment, 200);
    } else {
      $this->fail(500, '', array('暂无评论'));
    }
  }

  /**
   * 曲谱录音关系记录
   */
  public function saveRecordUrl($param)
  {
    if (empty($param['uid']) || empty($param['sheet_id']) || empty($param['url']) || empty($param['duration'])) {
      $this->fail(600);
    }
    $service = new SheetRecordService();
    try {
      $id = $service->save($param);
      $this->success('', 200);
    } catch (\Exception $e) {
      $this->fail(500, '', $e->getMessage());
    }
  }

  /**
   * 获取曲谱的用户录音
   */
  public function getSheetRecord($param)
  {
    if (empty($param['sheet_id'])) {
      $this->fail(600);
    }

    $service = new SheetRecordService();
    $list = $service->getUrlByParam($param);
    $this->success($list, 200);
  }

  /**
   * 删除曲谱录音
   */
  public function delRecord($param)
  {
    if (empty($param['uid']) || empty($param['record_id'])) {
      $this->fail(600);
    }

    $service = new SheetRecordService();
    $res = $service->del($param);
    if ($res === false) {
      $this->fail(500, '', array('该录音非此用户所有'));
    } elseif ($res) {
      $this->success('', 200);
    } else {
      $this->fail(500);
    }
  }

  /**
   * 记录录音播放次数
   */
  public function playCount($param)
  {
    //每日播放次数，时间记录到日（播放次数表，1.新建  2.增加记录次数）
    if (date('G') < '5') {
      $date = date('Ymd') - 1;
    } else {
      $date = date('Ymd');
    }

    $map = array(
      'record_id' => $param['id'],
      'date' => $date,
      'is_delete' => 0
    );
    //更新日播放统计
    $model = M('RecordPlayCount');
    $res = $model->where($map)->select();
    if ($res) {
      $id = $model->where($map)->setInc('play_count');
    } else {
      $data = array(
        'record_id' => $param['id'],
        'date' => $date,
        'play_count' => 1,
        'is_delete' => 0,
      );
      $id = $model->add($data);
    }
    //更新周排行统计
    $week = date('YW');
    $cond = array(
      'week' => $week,
      'record_id' => $param['id']
    );
    $weeklyRecord = M('RecordPlayCountWeek')->where($cond)->find();
    if ($weeklyRecord) {
      M('RecordPlayCountWeek')->where($cond)->setInc('play_count');
    }
    $this->success($id);
  }

  /**
   * 获取曲谱录音日排行
   */
  public function dailyRank($param)
  {
    if (date('G') < '5') {
      $date = date('Ymd') - 1;
    } else {
      $date = date('Ymd');
    }
    $map = array(
      'is_delete' => 0,
      'date' => $date,
    );
    $model = M('RecordPlayCount');
    $count = $model->where($map)->limit('100')->count();
    $listRows = empty($param['listRows']) ? 20 : $param['listRows'];
    $page = new PageService($param, $count, $listRows);
    $show = $page->show();
    //子查询，获取排名前100的数据
    $subQuery = $model->where($map)->field('id, record_id, date, play_count')->order('play_count')->limit('100');
    $list = $subQuery->limit($page->firstRow . ',' . $page->listRows)->select();

    $service = new SheetRecordService();
    $recordInfo = $service->recordInfo($list);
    foreach ($list as $key => $record) {
      $tar = $recordInfo[$record['record_id']];
      $list[$key]['url'] = $tar['url'];
      $list[$key]['duration'] = $tar['duration'];
      $list[$key]['user'] = $tar['user'];
      $list[$key]['sheet'] = $tar['sheet'];

    }

    $rankList['rank'] = $list ? $list : array();
    $rankList['nowPage'] = $page->nowPage;
    $rankList['totalCount'] = $count;
    $rankList['totalPage'] = ceil($count / $listRows);
    $this->success($rankList);
  }

  /**
   * 日排行前20名计入周排行
   */
  public function addToWeekRank()
  {
    //周日晚9点排名前20的用户录音计入周排行
    if (date('N') == 7) {
      $date = date('Ymd');
    } else {
      $date = date('Ymd') - 1;
    }
    echo $date;
    $week = date('YW');
    $weekRankRecord = M('RecordPlayCountWeek')->where(array('week' => $week))->select();

    $map = array(
      'date' => $date,
      'is_delete' => 0
    );
    $dailyRank = M('RecordPlayCount')->where($map)->field('record_id, play_count, date')
      ->order('play_count')->limit(20)->select();
    Log::writeInfo($date . ': daily record rank top 20:' . json_encode($dailyRank), 'weeklyRecordRank');
    $dailyRankIds = array_column($dailyRank, 'record_id');
    foreach ($dailyRank as $key => $record) {
      $data[$record['record_id']] = $record;
      $data[$record['record_id']]['week'] = $week;
    }

    //剔除已进入周排行的录音
    if (!empty($weekRankRecord)) {
      $weekRankRecordIds = array_column($weekRankRecord, 'record_id');
      $addToWeekIds = array_diff($dailyRankIds, $weekRankRecordIds);
      if ($addToWeekIds) {
        foreach ($addToWeekIds as $id) {
          $addToWeekRecord[] = $data[$id];
        }
        $id = M('RecordPlayCountWeek')->addAll($addToWeekRecord);
        Log::writeInfo($date . ':enter weekly record rank\'s Record: ' . json_encode($addToWeekRecord), 'weeklyRecordRank');
      }
    } else {
      foreach ($data as $record) {
        $id = M('RecordPlayCountWeek')->add($record);
      }
      Log::writeInfo($date . ':enter weekly record rank\'s Record: ' . json_encode($data), 'weeklyRecordRank');
    }
  }

  /**
   * 获取曲谱录音周排行
   */
  public function weeklyRank($param)
  {
    $week = date('YW');
    $map = array(
      'is_delete' => 0,
      'week' => $week,
    );

    $model = M('RecordPlayCountWeek');
    $count = $model->where($map)->limit('100')->count();
    $listRows = empty($param['listRows']) ? 20 : $param['listRows'];
    $page = new PageService($param, $count, $listRows);
    $show = $page->show();
    //子查询，获取排名前100的数据
    $subQuery = $model->where($map)->field('id, record_id, play_count')->order('play_count')->limit(100);
    // 截取分页
    $list = $subQuery->limit($page->firstRow . ',' . $page->listRows)->select();

    $service = new SheetRecordService();
    $recordInfo = $service->recordInfo($list);
    foreach ($list as $key => $record) {
      $list[$key]['url'] = $recordInfo[$record['record_id']]['url'];
      $list[$key]['user'] = $recordInfo[$record['record_id']]['user'];
      $list[$key]['sheet'] = $recordInfo[$record['record_id']]['sheet'];
    }

    $rankList['rank'] = $list ? $list : array();
    $rankList['nowPage'] = $page->nowPage;
    $rankList['totalCount'] = $count;
    $rankList['totalPage'] = ceil($count / $listRows);
    $this->success($rankList);
  }

  /**
   * 获取个人打榜情况
   */
  public function personalRankingList($param)
  {
    if (date('G') < '5') {
      $date = date('Ymd') - 1; //5点前取前一天的记录
    } else {
      $date = date('Ymd');
    }
    $map = array(
      'user_id' => $param['uid'],
      'is_delete' => 0
    );
    $list = M('SheetRecord')->where($map)->field('id, sheet_id')->select();
    if (!empty($list)) {
      $recordIds = array_column($list, 'id');
      $cond = array(
        'date' => $date,
        'record_id' => array('in', $recordIds),
      );
      $recordList = M('RecordPlayCount')->where($cond)->field('id, record_id, play_count')->order('play_count desc')->select();
      $service = new SheetRecordService();
      $recordInfo = $service->recordInfo($recordList);
      foreach ($recordList as $key => $record) {
        $recordList[$key]['url'] = $recordInfo[$record['record_id']]['url'];
        $recordList[$key]['user'] = $recordInfo[$record['record_id']]['user'];
        $recordList[$key]['sheet'] = $recordInfo[$record['record_id']]['sheet'];
      }
      $this->success($recordList);
    } else {
      $this->success(array());
    }
  }

}